import 'dart:async';

import 'package:alipay_kit/alipay_kit.dart';
import 'package:flutter/widgets.dart';

export 'package:alipay_kit/alipay_kit.dart';

typedef AlipayListener = void Function(AlipayResp response);

class AlipayBuilder extends StatefulWidget {
  final Alipay alipay;
  final WidgetBuilder builder;
  final AlipayListener payRespListener;

  const AlipayBuilder({
    @required this.alipay,
    @required this.builder,
    this.payRespListener,
  });

  @override
  State<StatefulWidget> createState() {
    return _AlipayBuilderState();
  }
}

class _AlipayBuilderState extends State<AlipayBuilder> {
  StreamSubscription<AlipayResp> _payRespSubscription;

  @override
  void initState() {
    super.initState();

    if (widget.payRespListener != null) {
      _payRespSubscription =
          widget.alipay.payResp().listen(widget.payRespListener);
    }
  }

  @override
  void dispose() {
    super.dispose();

    _payRespSubscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(context);
  }
}
